package com.srwl.mytx.dao;

import android.database.sqlite.SQLiteDatabase;

import com.srwl.mytx.Constant;
import com.srwl.mytx.MyApplication;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.greendao.DaoMaster;
import com.srwl.mytx.greendao.DaoSession;
import com.srwl.mytx.parse.UserProfileManager;

/**
 * Created by dahai2070 on 2018/5/9 0009.
 */

public class DBManager {
    private static DBManager ourInstance;
    private final DaoSession daoSession;
    private final SQLiteDatabase db;
    private DaoMaster.OpenHelper openHelper;

    //加上synchronized，是为了防止new 了多个DBManager
    public static synchronized DBManager getInstance() {
        if (ourInstance == null) {
            ourInstance = new DBManager();
        }
        return ourInstance;
    }

    private DBManager() {
        openHelper = new MyOpenHelper(MyApplication.getInstance().getApplicationContext(), getUserDatabaseName(), null);
        db = openHelper.getWritableDatabase();
        // 注意：该数据库连接属于 DaoMaster，所以多个 Session 指的是相同的数据库连接。
        DaoMaster daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
    }

    public DaoSession getDaoSession() {
        return daoSession;
    }

    private static String getUserDatabaseName() {
        String databaseName;
        User loginUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
        switch (loginUserInfo.getType()) {

            case Constant.USER_TYPE_NORMAL:
                databaseName = loginUserInfo.getPhone() + ".db";
                break;
            case Constant.USER_TYPE_ALI:
                databaseName = loginUserInfo.getAliAccount() + ".db";
                break;
            case Constant.USER_TYPE_TEMP:
            default:
                databaseName = "temp.db";
                break;
        }

        return databaseName;
    }


    /**
     * 关闭数据库,
     */
    synchronized public void closeDB() {
        if (db != null) {
            db.close();
        }
        openHelper = null;
        ourInstance = null;
    }

}
